package com.cswnode.Controller;

import com.cswnode.Annotations.LoginJudgment;
import com.cswnode.Entity.User;
import com.cswnode.Service.FollowerService;
import com.cswnode.Service.LikeService;
import com.cswnode.Service.UserService;
import com.cswnode.Util.CommunityUtil;
import com.cswnode.Util.Constant;
import com.cswnode.Util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * @author csw
 * @create 2020/9/19 20:12
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @Value("${server.servlet.context-path}")
    private String ContextPath;

    @Value("${community.path.domain}")
    private String domian;

    @Value("${community.path.upload}")
    private String upload;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowerService followerService;

    @LoginJudgment
    @GetMapping("/setting")
    public String toSettingPage(){
        return "/site/setting";
    }

    //上传头像
    @LoginJudgment
    @PostMapping("/upload")
    public String upLoadHeader(MultipartFile headerImage,Model model){
        if (headerImage == null){
            model.addAttribute("error","文件名为空！");
            return "/site/setting";
        }
        //后缀
        String fileName = headerImage.getOriginalFilename();
        int fileNameIndex = fileName.lastIndexOf(".");
        String suffix = null;
        if (fileNameIndex != -1){
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        if (StringUtils.isBlank(suffix)){
            model.addAttribute("error","上传得文件类型错误！");
            return "/site/setting";
        }
        //生成随机的文字名
        fileName = CommunityUtil.getUUID() + suffix;
        //确定存放的路径
        File desc = new File(upload + "/" + fileName);
        try {
            headerImage.transferTo(desc);
        } catch (IOException e) {
            logger.error("上传文件失败！"+e.getMessage());
            throw new RuntimeException("上传文件失败！服务器异常");
        }
        //更新头像路径
        //http://localhost:8081/community/user/header/***.jpg
        String headerUrl = domian + ContextPath + "/user/header/" + fileName;
        userService.updateHeaderUrl(hostHolder.getUser().getId(),headerUrl);
        return "redirect:/";
    }

    @GetMapping("/header/{fileName}")
    public void getHeader(HttpServletResponse response, @PathVariable("fileName")String fileName){
        //服务器存放的路径
        fileName = upload + "/" + fileName;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("image/"+suffix);
        try (
                OutputStream outputStream = response.getOutputStream();
                FileInputStream fileInputStream = new FileInputStream(fileName);
                ){
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("/读取头像失败"+e.getMessage());
        }
    }
    @LoginJudgment
    @PostMapping("/updatePassword")
    public String updatePassword(String oldPassword,String newPassword,Model model){
        User user = hostHolder.getUser();
        Map<String, String> map = userService.updatePassword(user.getId(), oldPassword, newPassword);
        if (!map.isEmpty()){
            model.addAttribute("passwordError",map.get("passwordError"));
            return "/site/setting";
        }
        model.addAttribute("passwordSuccess","修改成功！");
        return "/site/setting";
    }


    @GetMapping("/HomePage/{userId}")
    public String toHomePage(@PathVariable("userId")Integer userId,Model model){
        User user = userService.findUserById(userId);
        if (user == null){
            throw new RuntimeException("该用户不存在！");
        }
        int userLikeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("user",user);
        model.addAttribute("UserlikeCount",userLikeCount);
        //关注的数量
        long followerCount = followerService.findFollowerCount(userId, Constant.ENTITY_TYPE_USER);
        //粉丝的数量
        long fansCount = followerService.findFansCount(userId,Constant.ENTITY_TYPE_USER);
        Boolean followerStatus = false;
        if (hostHolder.getUser() != null){
            //查询是否已关注
            followerStatus = followerService.findFollowerStatus(hostHolder.getUser().getId(),userId,Constant.ENTITY_TYPE_USER);
        }
        model.addAttribute("followerCount",followerCount);
        model.addAttribute("fansCount",fansCount);
        model.addAttribute("followerStatus",followerStatus);
        return "/site/profile";
    }

}
